const { ObjectId } = require('mongodb');

const worldNewsCollection = 'worldNews';
const userProfileCollection = 'userProfile';

const queryWorldNews = (aggregate) => async (req, res) => {
    const pipeline = [
        {
            $lookup: {
                from: userProfileCollection,
                localField: 'sender',
                foreignField: '_id',
                as: 'sender'
            }
        },
        {
            $project: {
                'sender.password': 0,
                'sender.lastUpdate': 0,
                'sender.thumbsUp': 0,
                'sender.thumbsDown': 0,
                'sender.mail': 0,
            }
        }
    ]
    const result = await aggregate({ collection: worldNewsCollection, pipeline });
    res.json(result);
}

const sendWorldNews = (insertOne) => async (req, res) => {
    const { content } = req.payload;
    const { _id, username, role } = req.userInfo;
    const item = { content, sender: ObjectId(_id) };
    const insert = await insertOne(worldNewsCollection, item);
    const newsId = insert.insertedId;
    if (newsId) {
        const sender = [{ _id, username, role }];
        res.json({ content, sender, _id: newsId });
    } else res.status(500).json({ message: '发送失败' })
}

module.exports = { sendWorldNews, queryWorldNews }